package org.hs.phd.odi.transformation;

import java.awt.Polygon;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;

public final class ODIUtils {

	private static final double TWO_PI = 2*Math.PI;


	private ODIUtils(){
		
	}
	
	
	public static Rectangle2D.Double getBoundsOnTheSphere( ODITransformation transformation, Polygon polygon) {

		double maxTheta = Double.MIN_VALUE;
		double minTheta = Double.MAX_VALUE;
		double maxPhi = Double.MIN_VALUE;
		double minPhi = Double.MAX_VALUE;
		
		for(int i = 0; i < polygon.npoints; i++ ){
			Point2D.Double pointOnSphere = 
					transformation.imageToSphere(polygon.xpoints[i], polygon.ypoints[i]);
			
			double theta = pointOnSphere.x;
			if(theta < 0 ) theta = -theta;
			if(theta > Math.PI) theta = TWO_PI - theta;
			
			double phi = pointOnSphere.y;
			if(phi > TWO_PI) phi = phi % TWO_PI;
			if(phi < 0) phi += TWO_PI;
			
			
			
			if(theta > maxTheta ) maxTheta = theta;
			if(theta < minTheta ) minTheta = theta;
			if(phi > maxPhi ) maxPhi = phi;
			if(phi < minPhi ) minPhi = phi;
			
		}
		
		double widthPhi = maxPhi - minPhi;
		if(widthPhi > Math.PI){
			double temp = minPhi;
			minPhi = maxPhi;
			maxPhi = temp;
			widthPhi = TWO_PI - widthPhi;
		}
		
		return new Rectangle2D.Double( minTheta, minPhi, maxTheta - minTheta, widthPhi );
	}
	
}
